package com.tools.app.ui.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.LinearLayout;

import com.hm.base.android.ui.util.ScreenUtil;

/**
 * desc: Dialog 的基础类，提供Dialog的基本设置
 * date: 2017/8/10 14:28
 * author: ancun
 */
public abstract class ABaseDialog<T extends ABaseDialog<T>> extends Dialog {
    /**
     * 上下文
     */
    protected Context mContext;
    /**
     * 最上层容器
     */
    protected LinearLayout mDialogLayout;
    /**
     * 用于控制对话框高度,dialog动画即作用在此View上
     */
    protected LinearLayout mDialogHeight;
    /**
     * 布局填充创建出来的mDialogHeight的直接子View
     */
    protected View mDialogContent;
    /**
     * 设备密度
     */
    protected DisplayMetrics mDisplayMetrics;
    /**
     * Handler 定时器
     */
    private Handler mHandler;
    /**
     * 宽度比例
     */
    protected float mWidthScale = 1;
    /**
     * 高度比例
     */
    protected float mHeightScale;
    /**
     * 最大高度
     */
    protected float mMaxHeight;
    /**
     * 像PopupWindow一样展示Dialog
     */
    private boolean mIsPopupStyle;
    /**
     * 设置点击对话框以外区域,是否dismiss
     */
    protected boolean mCancel;
    /**
     * 在给定时间后,自动消失
     */
    private boolean mAutoDismiss;
    /**
     * 对话框消失延时时间,毫秒值
     */
    private long mAutoDismissDelay;

    /**
     * Dialog流程:
     * show : constructor---show---onCreate---onStart---onAttachToWindow
     * dismiss : dismiss---onDetachedFromWindow---onStop
     */
    public ABaseDialog(Context context) {
        super(context);
        setDialogTheme();
        mContext = context;
        setCanceledOnTouchOutside(true);
    }

    public ABaseDialog(Context context, boolean isPopupStyle) {
        this(context);
        mIsPopupStyle = isPopupStyle;
    }


    public ABaseDialog(Context context, int theme) {
        super(context, theme);
        mIsPopupStyle = false;
    }

    /**
     * 设置对话框主题
     */
    private void setDialogTheme() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);// android:windowNoTitle
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));// android:windowBackground
        getWindow().addFlags(LayoutParams.FLAG_DIM_BEHIND);// android:backgroundDimEnabled默认是true的
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mDisplayMetrics = mContext.getResources().getDisplayMetrics();
        mMaxHeight = mDisplayMetrics.heightPixels - ScreenUtil.getStatusHeight(mContext);

        mDialogLayout = new LinearLayout(mContext);
        mDialogLayout.setGravity(Gravity.CENTER);

        mDialogHeight = new LinearLayout(mContext);
        mDialogHeight.setOrientation(LinearLayout.VERTICAL);

        mDialogContent = onCreateView();
        mDialogHeight.addView(mDialogContent);
        mDialogLayout.addView(mDialogHeight);

        if (mIsPopupStyle) {
            setContentView(mDialogLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        } else {
            setContentView(mDialogLayout, new ViewGroup.LayoutParams(mDisplayMetrics.widthPixels, (int) mMaxHeight));
        }

        mDialogLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCancel) {
                    dismiss();
                }
            }
        });

        mDialogContent.setClickable(true);
    }

    /**
     * 当dialog依附在window上,设置对话框宽高以及显示动画
     */
    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();

        initDialogContent();

        int width;
        if (mWidthScale == 0) {
            width = ViewGroup.LayoutParams.WRAP_CONTENT;
        } else {
            width = (int) (mDisplayMetrics.widthPixels * mWidthScale);
        }

        int height;
        if (mHeightScale == 0) {
            height = ViewGroup.LayoutParams.WRAP_CONTENT;
        } else if (mHeightScale == 1) {
            height = (int) mMaxHeight;
        } else {
            height = (int) (mMaxHeight * mHeightScale);
        }

        mDialogHeight.setLayoutParams(new LinearLayout.LayoutParams(width, height));

        //BaseDialogAnimatorSet.reset(mDialogHeight);
        delayDismiss();
    }


    @Override
    public void setCanceledOnTouchOutside(boolean cancel) {
        this.mCancel = cancel;
        super.setCanceledOnTouchOutside(cancel);
    }

    @Override
    public void dismiss() {
        superDismiss();
    }

    /**
     * 动画弹出对话框,style动画资源
     */
    public void show(int animStyle) {
        Window window = getWindow();
        window.setWindowAnimations(animStyle);
        show();
    }

    @Override
    public void show() {
        if (mContext == null) {
            return;
        }
        if (mContext instanceof Activity) {
            if (((Activity) mContext).isFinishing()) {
                return;
            }
        }
        super.show();
    }

    /**
     * 无动画dismiss
     */
    public void superDismiss() {
        super.dismiss();
    }

    /**
     * 指定位置显示,只对isPopupStyle为true有效
     */
    public void showAtLocation(int gravity, int x, int y) {
        if (mIsPopupStyle) {
            Window window = getWindow();
            LayoutParams params = window.getAttributes();
            window.setGravity(gravity);
            params.x = x;
            params.y = y;
        }

        show();
    }

    /**
     * 指定位置显示,只对isPopupStyle为true有效
     */
    public void showAtLocation(int x, int y) {
        int gravity = Gravity.LEFT | Gravity.TOP;//Left Top (坐标原点为右上角)
        showAtLocation(gravity, x, y);
    }

    /**
     * 设置背景是否昏暗
     */
    public T dimEnabled(boolean isDimEnabled) {
        if (isDimEnabled) {
            getWindow().addFlags(LayoutParams.FLAG_DIM_BEHIND);
        } else {
            getWindow().clearFlags(LayoutParams.FLAG_DIM_BEHIND);
        }
        return (T) this;
    }

    /**
     * 设置对话框宽度,占屏幕宽的比例0-1
     */
    public T widthScale(float widthScale) {
        this.mWidthScale = widthScale;
        return (T) this;
    }

    /**
     * 设置对话框高度,占屏幕宽的比例0-1
     */
    public T heightScale(float heightScale) {
        mHeightScale = heightScale;
        return (T) this;
    }

    /**
     * 在给定时间后,自动消失
     */
    public T autoDismiss(boolean autoDismiss) {
        mAutoDismiss = autoDismiss;
        return (T) this;
    }

    /**
     * 对话框消失延时时间,毫秒值
     */
    public T autoDismissDelay(long autoDismissDelay) {
        mAutoDismissDelay = autoDismissDelay;
        return (T) this;
    }

    private void delayDismiss() {
        if (mAutoDismiss && mAutoDismissDelay > 0) {

            if (mHandler == null) {
                mHandler = new Handler(Looper.getMainLooper());
            }
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    dismiss();
                }
            }, mAutoDismissDelay);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mAutoDismiss) {
            return true;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onBackPressed() {
        if (mAutoDismiss) {
            return;
        }
        super.onBackPressed();
    }

    /**
     * 填充对话框所需要的布局并返回
     */
    public abstract View onCreateView();

    /**
     * 在对话框显示之前,设置界面数据或者逻辑
     */
    public abstract void initDialogContent();

}
